<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { ItemRecptLine } from '#/api';

import { defineOptions, defineProps, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton, VxeGrid } from '@vben/plugins/vxe-table';

import { Divider } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteItemRecptLine,
  getItemRecptLineAndDetailTableList,
  getItemRecptLineTableList,
} from '#/api';
import { mergeToolbarButtons, updateToolbarButtonStatus } from '#/utils';

import { confirm, messageError, messageSuccess } from '../../common/common';
import { useItemRecptColumns } from './data';
import MaterialForm from './materialmodal.vue';

defineOptions({
  name: 'MaterialTableGrid',
});
const props = defineProps<{
  attr1: string;
  id: number;
  status: string;
}>();

// 存储选中行的响应式变量
const selectedRows = ref<ItemRecptLine.Row[]>([]);
const btn = mergeToolbarButtons();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: MaterialForm,
  destroyOnClose: true,
});
/**
 * 查看
 * @param row
 */
function onView(row: ItemRecptLine.Row) {
  row.attr1 = '1';
  formModalApi.setData(row).open();
}

/**
 * 创建
 */
function onAdd() {
  formModalApi.setData({ recptId: props.id }).open();
}

/**
 * 编辑
 * @param row
 */
function onEdit(row: ItemRecptLine.Row) {
  row.attr1 = '2';
  formModalApi.setData(row).open();
}

/**
 * 删除
 * @param row
 */
function onDelete(row: ItemRecptLine.Row | ItemRecptLine.Row[]) {
  const ids = Array.isArray(row)
    ? row.map((item) => item.lineId)
    : [row.lineId];
  const idString = ids.join(',');
  confirm(`确定要删除物料入库单行编码为【${idString}】的数据吗？`, '提示').then(
    () => {
      deleteItemRecptLine(idString)
        .then(() => {
          messageSuccess(`删除成功`);
          refreshGrid();
        })
        .catch((error) => {
          messageError(error);
        });
    },
  );
}

/**
 * 处理物料信息表格操作列点击事件的函数
 *
 * @param {OnActionClickParams<ItemRecptLine.Row>} - 包含操作代码和行数据的对象
 */
function onActionClick({ code, row }: OnActionClickParams<ItemRecptLine.Row>) {
  switch (code) {
    case 'add': {
      onAdd();
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'myDelete': {
      onDelete(row);
      break;
    }
    case 'onView': {
      onView(row);
      break;
    }
    default: {
      break;
    }
  }
  updateToolbarButtonStatus(selectedRows, btn.value);
}

/* 物料信息表格配置 */
const materialGridOptions: VxeGridProps<ItemRecptLine.Row> = {
  columns: useItemRecptColumns(props.status, onView, onActionClick),
  checkboxConfig: {
    highlight: true,
  },

  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        if (props.status === 'PREPARE') {
          const res = await getItemRecptLineTableList({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            recptId: props.id,
          });
          return { items: res.rows, total: res.total };
        } else {
          const res = await getItemRecptLineAndDetailTableList({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            recptId: props.id,
          });
          return { items: res.rows, total: res.total };
        }
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    zoom: true,
    refresh: { code: 'query' },
    buttons:
      props.attr1 === '1' || props.status !== 'PREPARE'
        ? null
        : (btn.value as any),
  },
};

/* 物料信息表格事件 */
const materialGridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'add': {
        onAdd();
        break;
      }
      case 'edit': {
        if (selectedRows.value.length === 1) {
          onEdit(selectedRows.value[0] as any);
        } else {
          confirm('请选择单行', '提示');
        }
        break;
      }
      case 'myDelete': {
        console.warn('删除选中行:', selectedRows.value);
        onDelete(selectedRows.value);
        break;
      }
      default: {
        break;
      }
    }
  },

  checkboxChange() {
    selectedRows.value = materialTableGridApi?.grid?.getCheckboxRecords();
    updateToolbarButtonStatus(selectedRows, btn.value);
  },
  checkboxAll() {
    selectedRows.value = materialTableGridApi?.grid?.getCheckboxRecords();
    updateToolbarButtonStatus(selectedRows, btn.value);
  },
};

/* 物料信息表格实例 */
const [MaterialTableGrid, materialTableGridApi] = useVbenVxeGrid({
  gridEvents: materialGridEvents,
  gridOptions: materialGridOptions,
});

/* 仓库信息子表格 */
const childGridOptions: VxeGridProps<ItemRecptLine.Row> = {
  minHeight: 100,
  columns: [
    { field: 'warehouseName', title: '仓库名称' },
    { field: 'locationName', title: '库区名称' },
    { field: 'areaName', title: '库位名称', width: 135 },
    { field: 'quantity', title: '数量' },
  ],
  pagerConfig: { enabled: false },
  headerRowStyle: {
    backgroundColor: '#D9DEF2',
  },
};

/**
 * 刷新物料信息表格
 */
function refreshGrid() {
  materialTableGridApi.query();
}
/**
 * 提交表单后的处理函数
 * @param {string} msg - 提交成功后的提示信息
 */
function handleSubmit(msg: string) {
  messageSuccess(msg);
  refreshGrid();
}
</script>

<template>
  <Divider>物料信息</Divider>
  <MaterialTableGrid @success="handleSubmit">
    <template #expand_content="{ row }">
      <div class="expand-wrapper ml-[50px] w-[460px]">
        <VxeGrid
          v-bind="childGridOptions"
          :data="row.details"
          :style="{
            '--vxe-ui-table-border-width': '0px',
          }"
        />
      </div>
    </template>
    <template #action="{ row }">
      <div v-if="status === 'PREPARE' && attr1 !== '1'">
        <VxeButton
          mode="text"
          icon="vxe-icon-signature"
          @click="onActionClick({ code: 'edit', row })"
          status="primary"
        >
          编辑
        </VxeButton>
        <VxeButton
          icon="vxe-icon-delete"
          mode="text"
          @click="onActionClick({ code: 'myDelete', row })"
          status="error"
        >
          删除
        </VxeButton>
      </div>
    </template>
  </MaterialTableGrid>
  <FormModal @success="handleSubmit" />
</template>
